package com.project.service.impl;

import com.common.utils.StringUtils;
import com.project.domain.entity.xjProject.BizXjProject;
import com.project.domain.entity.zxProject.BizZxProject;
import com.project.mapper.xjProject.XjProjectMapper;
import com.project.mapper.zxProject.ZxProjectMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

@Service
public class upDateZBCheckInfo {

    public static <T> String upDateZBCheckInfo(SqlSession sqlSession, T obj, Class<T> clazz, String checkStatus, String processInstanceId){
        String res= "0";
        XjProjectMapper xjProjectMapper = sqlSession.getMapper(XjProjectMapper.class);
        ZxProjectMapper zxProjectMapper = sqlSession.getMapper(ZxProjectMapper.class);

        if (obj == null || clazz == null ) {
            throw new IllegalArgumentException("参数不能为空");
        }

        try{
            if(StringUtils.isNotBlank(checkStatus)){
                setField(obj, clazz, "checkStatus", checkStatus);
            }

            if(StringUtils.isNotBlank(processInstanceId)){
                setField(obj, clazz, "processInstanceId", processInstanceId);
            }

            if (obj instanceof BizXjProject) {
                BizXjProject xiObj = (BizXjProject) obj;
                res = String.valueOf(xjProjectMapper.updateById(xiObj));
            }

            if (obj instanceof BizZxProject) {
                BizZxProject zxObj = (BizZxProject) obj;
                res = String.valueOf(zxProjectMapper.updateById(zxObj));
            }

        }catch (NoSuchFieldException e) {
            res = "类 " + clazz.getSimpleName() + " 缺少必要的字段: " + e.getMessage();
        } catch (IllegalAccessException e) {
            res = "无法访问字段"+ e;
        }

        return res;
    }

    // 通用字段赋值方法
    private static <T> void setField(T obj, Class<T> clazz, String fieldName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }
}
